package com.example.controller.handle;

import com.alibaba.dubbo.config.annotation.Reference;
import com.example.common.api.user.service.LoginService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: wyj
 * @Description:登录功能的handler
 */
@Controller
public class LoginController {

    @Reference(version = "1.0.0")
    private LoginService loginService;

    @GetMapping("/loginServlet.do")
    public String login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //从表单中获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        System.out.println(username + "," + password + "," + rememberMe);

        //判断rememberMe是否记住用户名密码
        if (rememberMe != null) {
            Cookie cookie = new Cookie("rememberMe", username + "-" + password);
            cookie.setPath(request.getContextPath());//设置cookie保存路径在本网站根路径
            response.addCookie(cookie);
        }

        //调用service层方法
        String password1 = loginService.login(username);
        System.out.println("password1:" + password1);

        //比较用户名和密码
        if (password.equals(password1)) {
            request.getSession().setAttribute("username", username);
            return "index";
        } else {
            return "login";
        }
    }

}
